// Mongoose
const mongoose = require('mongoose')

// Schema
const MemorySchema = require('../schema/MemorySchema');
const ErrorSchema = require('../schema/ErrorSchema');
const StaticSchema = require('../schema/StaticSchema');
const XHRSchema = require('../schema/XHRSchema');

//Utils
const utils = require('./index.js');

// Connection
mongoose.connect('mongodb://localhost/report', { useNewUrlParser: true })
    .then(() => console.log("mongoDB Connection Success!"))
    .catch(e => console.log(e))


module.exports = (params) => {
    return new Promise((resolve, reject) => {
        switch (params.type) {
            case 'static':
                console.log('保存static')
                const static = new StaticSchema(
                    Object.assign(params.info, {
                        id: utils.guid(),
                        timeStamp: new Date().getTime()
                    })
                );
                static.save()
                    .then(res => {
                        resolve(res);
                    })
                    .catch(e => {
                        reject(e);
                    })
                break;
            case 'error':
                console.log('保存error')
                const err = new ErrorSchema(
                    Object.assign(params.info, {
                        id: utils.guid(),
                        timeStamp: new Date().getTime()
                    })
                );
                err.save()
                    .then(res => {
                        resolve(res);
                    })
                    .catch(e => {
                        reject(e);
                    })
                break;
            case 'memory':
                console.log('保存memory')
                const memory = new MemorySchema(
                    Object.assign(params.info, {
                        id: utils.guid(),
                        timeStamp: new Date().getTime()
                    })
                );
                memory.save()
                    .then(res => {
                        resolve(res);
                    })
                    .catch(e => {
                        reject(e);
                    })
                break;
            case 'xhr':
                console.log('保存xhr')
                const xhr = new XHRSchema(
                    Object.assign(params.info, {
                        id: utils.guid(),
                        timeStamp: new Date().getTime()
                    })
                );
                xhr.save()
                    .then(res => {
                        console.log(res);
                        resolve(res);
                    })
                    .catch(e => {
                        console.log(e);
                        reject(e);
                    })
                break;
        }
    })
}